<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'Form',
  props: {
    mode: {
      type: Object,
      default: () => ({})
    },
    rule: {
      type: Object,
      default: () => ({})
    }
  },
  methods: {
    validate () {
      const data = this.mode
      let errorMessage = ''
      let flg = true
      for (const key in data) {
        if (this.rule[key] instanceof Array) {
          const rule = this.rule[key]
          for (let i = 0; i < rule.length; i++) {
            flg = this._check(key, data[key], rule[i])
            if (!flg) {
              errorMessage = rule[i].message
              break
            }
          }
        } else if (this.rule[key]) {
          flg = this._check(key, data[key], this.rule[key])
          if (!flg) {
            errorMessage = this.rule[key].message
          }
        }

        if (!flg) {
          break
        }
      }
      if (flg) {
        return Promise.resolve()
      } else {
        return Promise.reject(errorMessage)
      }
    },
    _check (key, val, rule) {
      console.log(rule)
      if (rule.required && !val) {
        return false
      } else if (rule.reg && !rule.reg.test(val)) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
